/**
 * @(#) CongMoneyMediator.as
 *
 * @date		2009. 03. 25.
 * @version		1.0
 * @author		baek, kwang hyoun
 * @description	의료금 신청 - Mediator
 * 				의료금을 조회하고 신청하는 Presentation Logic을 관리
 */
package com.skt.common_hr.medicalmoney_sac.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.medicalmoney_sac.MedicalMoneyFacade;
	import com.skt.common_hr.medicalmoney_sac.events.ComboBoxYearEvent;
	import com.skt.common_hr.medicalmoney_sac.events.mmGwarekeyEvent;
	import com.skt.common_hr.medicalmoney_sac.model.CelebrationCodeProxy;
	import com.skt.common_hr.medicalmoney_sac.model.MedicalMoneyProxy;
	import com.skt.common_hr.medicalmoney_sac.model.ReqMedicalMoneyWriteProxy;
	import com.skt.common_hr.medicalmoney_sac.model.StatementUrlProxy;
	import com.skt.common_hr.medicalmoney_sac.model.SupportStandardProxy;
	import com.skt.common_hr.medicalmoney_sac.view.components.MedicalMoneyOverViewSac;
	
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.net.navigateToURL;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class MedicalMoneyMediator extends OverViewMediator
	{
		public static const NAME:String = "MedicalMoneyMediator";


		/**
		* 생성자
		*
		* @param
		* @return void
		*/
        public function MedicalMoneyMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }

		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		* 최초 한번만 불림
		*/
 		override protected function initializeView():void
 		{
 			loadSupportStandard(); // 현재 하는짓 없음.
			super.initializeView();
 		}
		/***
		 * 활성화가 될때마다 불림.
		 */
		override protected function activatedView():void
		{
			super.activatedView();
			
			yearSetting();
			
 			loadList();
			setEventListener();
 			view.vsCompensation.selectedIndex = 0;
		}
		
		public function yearSetting():void
		{
			var dYear:Date = new Date();
			var sYear:String = (dYear.fullYear).toString();
			
			for(var i:int=0; i<view.acYear.length; i++) {
				if(sYear == view.acYear.getItemAt(i).label){
					view.cbYear.selectedIndex = i;
				}
			}
			
			//ArrayHelper.indexOf(acYear, data, cbYear)
		}

		override protected function closedView():void
		{
			removeEventListener();
		}

 		private function setEventListener():void
 		{
 			// 의료비 신청버튼
 			view.addEventListener(MedicalMoneyOverViewSac.MedicalMoneyWrite, onClickNew);
 			//view.addEventListener(MedicalMoneyOverView.MedicalMoneyWrite, onMedicalWriteOpen);



			view.addEventListener(mmGwarekeyEvent.SELECT_DATA, onClickReadOnly);
			view.addEventListener(mmGwarekeyEvent.UPDATE_DATA, onClickModify);
			view.addEventListener(mmGwarekeyEvent.DELETE_DATA, onClickDelete);
			view.addEventListener(mmGwarekeyEvent.PRINT_DATA, onStatementView);
			view.addEventListener(mmGwarekeyEvent.PRINT_DATA2, onStatementViewAttach);

			//silver
			view.addEventListener(ComboBoxYearEvent.SELECT_YEAR_DATA, onComboYear);
 		}

 		private function removeEventListener():void
 		{
 			// 신청
 			view.addEventListener(MedicalMoneyOverViewSac.MedicalMoneyWrite, onClickNew);

 			//view.removeEventListener(MedicalMoneyOverView.MedicalMoneyWrite, onMedicalWriteOpen);


			view.removeEventListener(mmGwarekeyEvent.SELECT_DATA, onClickReadOnly);
			view.removeEventListener(mmGwarekeyEvent.UPDATE_DATA, onClickModify);
			view.removeEventListener(mmGwarekeyEvent.DELETE_DATA, onClickDelete);
			view.removeEventListener(mmGwarekeyEvent.PRINT_DATA, onStatementView);
			view.removeEventListener(mmGwarekeyEvent.PRINT_DATA2, onStatementViewAttach);

			//silver
			view.removeEventListener(ComboBoxYearEvent.SELECT_YEAR_DATA, onComboYear);
			//view.removeEventListener(ItemCongClickEvent.CONG_ITEM_CLICK, onStatementView);

			//view.medicalmoneyDetailView.removeEventListener(MedicalMoneyDetailView.ClosedDetailView, onCloseDetailView);
 		}


 
 		private function loadList():void  
 		{
 			var mProxy:MedicalMoneyProxy = facade.retrieveProxy(MedicalMoneyProxy.NAME) as MedicalMoneyProxy;
			mProxy.loadList(Variables.myPernr);
 		}

 		private function loadSupportStandard():void
 		{
 			/*
 			var proxy:SupportStandardProxy = facade.retrieveProxy(SupportStandardProxy.NAME) as SupportStandardProxy;
 			proxy.load(Variables.myPernr);

 			var codeProxy:CelebrationCodeProxy = facade.retrieveProxy(CelebrationCodeProxy.NAME) as CelebrationCodeProxy;
 			var begin:Date = DateUtil.todayNoTime();
 			begin.month -= 6;
 			var end:Date = DateUtil.todayNoTime();
 			end.month += 6;
 			codeProxy.loadHolidays(begin, end);
 			 */
 		}





		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		*
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array
		{
			return basicInterestMessages.concat([
					// reload
					ReqMedicalMoneyMediator.CLOSED_REQUEST_VIEW,


					MedicalMoneyProxy.LOAD_MEDICALMONEY_LIST_COMPLETE,
					MedicalMoneyProxy.LOAD_MEDICALMONEY_LIST_FAILED,

					MedicalMoneyFacade.LOAD_MEDICALMONEY_DETAIL_COMPLETE,
					MedicalMoneyFacade.LOAD_MEDICALMONEY_DETAIL_FAILED,

					MedicalMoneyFacade.LOAD_MEDICALMONEY_PRINT_COMPLETE,
					MedicalMoneyFacade.LOAD_MEDICALMONEY_PRINT_FAILED,


					MedicalMoneyFacade.LOAD_CELEBRATION_LIST_COMPLETE,
					MedicalMoneyFacade.LOAD_CELEBRATION_LIST_FAILED,
					MedicalMoneyFacade.LOAD_CONGMONEY_SAVE_COMPLETE,
					MedicalMoneyFacade.LOAD_CONGMONEY_SAVE_FAILED,
					MedicalMoneyFacade.LOAD_CONGMONEY_DELETE_COMPLETE,
					MedicalMoneyFacade.LOAD_CONGMONEY_DELETE_FAILED,

					MedicalMoneyFacade.LOAD_CONGMONEY_PRINT_COMPLETE,
					MedicalMoneyFacade.LOAD_CONGMONEY_PRINT_FAILED,
					MedicalMoneyFacade.LOAD_CONGMONEY_SAVEFAL_FAILED,
					MedicalMoneyFacade.LOAD_CONGMONEY_CORSNVIEW_COMPLETE,
					MedicalMoneyFacade.LOAD_CONGMONEY_CORSNVIEW_FAILED,
					ReqMedicalMoneyMediator.CLOSED_REQUEST_VIEW,
					CelebrationCodeProxy.LOAD_HOLIDAYS_COMPLETE,
					CelebrationCodeProxy.LOAD_HOLIDAYS_FAILED,

					StatementUrlProxy.LOAD_STATEMENT_URL_COMPLTE,
					StatementUrlProxy.LOAD_STATEMENT_URL_FAILED,

					SupportStandardProxy.LOAD_SUPPORT_STANDARD_COMPLETE,
					SupportStandardProxy.LOAD_SUPPORT_STANDARD_FAILED

					]);
		}


		/**
		* Noti별로 처리한다.
		*
		* @param
		* @return void
		*/
		public var sSpmon:String;
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName())
			{
				// 의료비 리스트  조회 Proxy 호출결과 처리
				case MedicalMoneyProxy.LOAD_MEDICALMONEY_LIST_COMPLETE :
					setListView(MedicalMoneyProxy(note.getBody()).mainList);
					sSpmon = MedicalMoneyProxy(note.getBody()).sSpmon;
					break;
				// 의료비 리스트 조회 실패시
				case MedicalMoneyProxy.LOAD_MEDICALMONEY_LIST_FAILED :
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_LOAD_LIST", null, "ALERT_TITLE_SYSTEM_ERROR");
					break;

				// 재조회
				case ReqMedicalMoneyMediator.CLOSED_REQUEST_VIEW:
					view.vsCompensation.selectedIndex = 0;
					loadList();
					break;

				case MedicalMoneyFacade.LOAD_MEDICALMONEY_PRINT_COMPLETE:
					onPrintDataLoad(note.getBody() as MedicalMoneyProxy);
					break;
				case MedicalMoneyFacade.LOAD_MEDICALMONEY_PRINT_FAILED:
					trace("LoadCongmoneyPrintFailed");
					break;
					
				case MedicalMoneyFacade.LOAD_MEDICALMONEY_DETAIL_COMPLETE:
					//setDetailView(MedicalMoneyProxy(note.getBody()).detailVO);
					break;
				case MedicalMoneyFacade.LOAD_MEDICALMONEY_DETAIL_FAILED:
					trace("LoadMEDICALMONEYSelectLoadFailed");
					break;
					
					
				// 리스트 조회 Proxy 호출결과 처리
				case MedicalMoneyFacade.LOAD_CELEBRATION_LIST_COMPLETE:
					setListView(MedicalMoneyProxy(note.getBody()).mainList);
					break;
				case MedicalMoneyFacade.LOAD_CELEBRATION_LIST_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_LOAD_LIST", null, "ALERT_TITLE_SYSTEM_ERROR");
					break;
				case MedicalMoneyFacade.LOAD_CONGMONEY_DELETE_COMPLETE:
					//삭제후 조회
					loadList();
					break;
				case MedicalMoneyFacade.LOAD_CONGMONEY_DELETE_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_DELETE", null, "ALERT_TITLE_SYSTEM_ERROR");
					break;





				case ReqMedicalMoneyMediator.CLOSED_REQUEST_VIEW:
					view.vsCompensation.selectedIndex = 0;
					loadList();
					break;
				case MedicalMoneyFacade.LOAD_CONGMONEY_SAVEFAL_FAILED:
					onSaveFailedErroryMessage(note.getBody() as ReqMedicalMoneyWriteProxy);
					break;
				case MedicalMoneyFacade.LOAD_CONGMONEY_CORSNVIEW_COMPLETE:
					onCorsnLoad(note.getBody() as MedicalMoneyProxy);
					break;
				case MedicalMoneyFacade.LOAD_CONGMONEY_CORSNVIEW_FAILED:
					//view.printView.doPrint();
					break;
				case CelebrationCodeProxy.LOAD_HOLIDAYS_COMPLETE:
					break;

				// 전표출력..
				case StatementUrlProxy.LOAD_STATEMENT_URL_COMPLTE:
					onNotePrint((note.getBody() as StatementUrlProxy).url);
					break;
				case StatementUrlProxy.LOAD_STATEMENT_URL_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "("+(note.getBody() as StatementUrlProxy).errCode+")"+ (note.getBody() as StatementUrlProxy).errText);
					break;

				// 대상자 변경가능 / 경조사 조회 가능 기간  받기...
				case SupportStandardProxy.LOAD_SUPPORT_STANDARD_COMPLETE:
					setSuuportStandard( SupportStandardProxy(note.getBody()).standardExport );
					break;
				case SupportStandardProxy.LOAD_SUPPORT_STANDARD_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, "("+(note.getBody() as StatementUrlProxy).errCode+")"+ (note.getBody() as StatementUrlProxy).errText);
					break;


				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}


 		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - load된 데이터를 화면에 출력
		 * @param
		 * @return void
		 */
 		private function setListView(list:ArrayCollection):void
 		{
 			view.medicalMoneyDataList = list;
 			commonFacade.setStatusMessage("STATUS_LOADED_LIST", [list.length.toString()]);
 			if(list.length == 0) {
 				view.showInitialTip();
 			}
 		}

		/**
		 * list조회가 성공했을 때 호출됨
		 *     - 조회상세보기
		 * @param
		 * @return void

 		private function setDetailView(vo:MedicalMoneyVO):void
 		{
 			var proxy:SupportStandardProxy = facade.retrieveProxy(SupportStandardProxy.NAME) as SupportStandardProxy;
 			view.medicalmoneyDetailView.dataProvider = vo;
 			//view.medicalmoneyDetailView.funeral = proxy.isFuneral(vo.CORSN);
 		}
		*/

		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - 프린트
		 * @param
		 * @return void
		 */
 		private function onPrintDataLoad(proxy:MedicalMoneyProxy):void
 		{
 			//PopUpManager.addPopUp(view.printView, view);
 			//PopUpManager.centerPopUp(view.printView);
 			if(Variables.company == "SAC") {
 				view.printViewSac.vo = proxy.printDataVO;
 			}
 			
 			//view.printView.doPrint();

 			//사유
 			var corsGubun:String;
// 			if(proxy.printDataVO.CPERNR == Variables.myPernr) {
//				corsGubun = ""; //본인인경우
//			} else {
//				corsGubun = "X"; //대상자병경시
//			}
/* 

			corsGubun = "";
			var corsnProxy:MedicalMoneyProxy = facade.retrieveProxy(MedicalMoneyProxy.NAME) as MedicalMoneyProxy;
			corsnProxy.corsnLoad(corsGubun);
			 */
 		}


  		//저장에러 메세지 휴가중복메세지
 		private function onSaveFailedErroryMessage(proxy:ReqMedicalMoneyWriteProxy):void
 		{
 			view.vsCompensation.selectedIndex = 0;
 			CommonAlert.showMessage(commonFacade.bundle, "ALERT_FAILED_SAVE");
 		}


 		//사유(프린트)
 		private function onCorsnLoad(proxy:MedicalMoneyProxy):void
 		{
 			var index:int;
// silver0405
// 			if(Variables.company == "SAC") {
//	 			index = findCodeIndex(view.printViewSac.vo.CORSN,proxy.congCorsn);
//
//	 			if(index != -1) {
//	 				view.printViewSac.cornm = proxy.congCorsn[index].label;
//	 			}
//
//	 			view.printViewSac.doPrint();
//	 		}
//	 		else {
//	 			index = findCodeIndex(view.printView.vo.CORSN,proxy.congCorsn);
//
//	 			if(index != -1) {
//	 				view.printView.cornm = proxy.congCorsn[index].label;
//	 			}
//
//	 			view.printView.doPrint();
//	 		}
 		}














		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////

		/**
		 * 의료비 조회버튼 이벤트 onClickModify
		 * @param
		 * @return void
		 */
 		private function onClickReadOnly(event:mmGwarekeyEvent):void
 		{
			var param:Object = new Object();
 			param.gwarekey  = event.key;
 			param.pernr = event.cpernr;
 			param.name  = Variables.myName;
 			param.write  = false;
			param.spmon = sSpmon;
 			executeReqView(param);
 		}

 		/**
		 * 의료비   신규 신청 버튼 처리
		 * @param
		 * @return void
		 */
 		private function onClickNew(event:Event):void
 		{
			if(sSpmon == '') {
				Alert.show('신청가능기간이 아닙니다.');
				return;
			}
 			var param:Object = new Object();
 			param.pernr 	= Variables.myPernr;
 			param.name  	= Variables.myName;
 			param.gwarekey  = "";
			param.write  	= true;
			param.spmon = sSpmon;
 			executeReqView(param);
 		}

 		/**
		 * 의료비 신규 신청 및 수정 화면 실행
		 * @param
		 * @return void
		 */
 		private function executeReqView(param:Object):void
 		{
 			commonFacade.setStatusMessage("");
			view.vsCompensation.selectedIndex = 1;
 			var writeMediator:ReqMedicalMoneyMediator = facade.retrieveMediator(ReqMedicalMoneyMediator.NAME) as ReqMedicalMoneyMediator;

 			if(!writeMediator) {
				writeMediator = new ReqMedicalMoneyMediator(view.medicalmoneyWriteView);
	 			facade.registerMediator(writeMediator);
			}
 			if(writeMediator) facade.sendNotification(MedicalMoneyFacade.LOAD_MEDICALMONEY_WRITE_INITIAL, param);
 		}

 		/**
		 * 의료비 수정 버튼 클릭시 실행
		 * @param
		 * @return void
		 */
 		private function onClickModify(event:mmGwarekeyEvent):void
 		{
			var param:Object = new Object();
 			param.gwarekey  = event.key;
 			param.pernr = event.cpernr;
 			param.name  = Variables.myName;
			param.write  	= true;
			param.spmon = sSpmon;
 			executeReqView(param);
 		}


 		/**
		 * 삭제 버튼 클릭시 실행
		 * @param
		 * @return void
		 */
 		private function onClickDelete(event:mmGwarekeyEvent):void
 		{
 			var mmProxy:MedicalMoneyProxy = facade.retrieveProxy(MedicalMoneyProxy.NAME) as MedicalMoneyProxy;
			mmProxy.deleteData(event.key, event.wstatus);
 		}



 		/**
		 * 의료비 프린트
		 * @param
		 * @return void
		 */
 		private function onClickPrint(event:mmGwarekeyEvent):void
 		{
 			var mmProxy:MedicalMoneyProxy = facade.retrieveProxy(MedicalMoneyProxy.NAME) as MedicalMoneyProxy;
			mmProxy.printData(event.key);
 		}

 		/**
		 * 년도 조회, silver
		 * @param
		 * @return void
		 */
 		private function onComboYear(event:ComboBoxYearEvent):void
 		{
 			var congProxy:MedicalMoneyProxy = facade.retrieveProxy(MedicalMoneyProxy.NAME) as MedicalMoneyProxy;
			congProxy.loadYearSearchList(Variables.myPernr, event.comData);
 		}

 		/**
		 * 전표조회, silver
		 * @param
		 * @return void
		 */
 		private function onStatementView(event:mmGwarekeyEvent):void
 		{
 			var statementProxy:StatementUrlProxy = facade.retrieveProxy(StatementUrlProxy.NAME) as StatementUrlProxy;
			statementProxy.load(event.key.toString());
 		}
		
		// 증빙첨부출력
 		private function onStatementViewAttach(event:mmGwarekeyEvent):void
 		{
 			var statementProxy:StatementUrlProxy = facade.retrieveProxy(StatementUrlProxy.NAME) as StatementUrlProxy;
			statementProxy.loadAttach(event.key.toString());
 		}
 		
 		/**
		 * 경조사 대상설정 변경가능 유무 및 기간 설정  정보 받아오기. silver
		 * @param
		 * @return void
		 */
/*  		private function onSupportStandard(event:):void
 		{
 			var statementProxy:StatementUrlProxy = facade.retrieveProxy(StatementUrlProxy.NAME) as StatementUrlProxy;
			statementProxy.load(event.item.GWAREKEY.toString());
 		}
 */


 		/**
		 * 경조사 조회닫기
		 * @param
		 * @return void
		 */
 		private function onCloseDetailView(event:Event):void
 		{
 			view.vsCompensation.selectedIndex = 0;
 			//setStatusMessage("");
 		}




		// 전표출력
		private function onNotePrint(url:String):void
		{
			var req:URLRequest = new URLRequest("../ace_medical/"+url);
			navigateToURL(req);
		}

		// 대상자 변경 가능 유무 및 기간 셋팅.
		private function setSuuportStandard(oExport:Object):void
		{
 			var writeMediator:ReqMedicalMoneyMediator = facade.retrieveMediator(ReqMedicalMoneyMediator.NAME) as ReqMedicalMoneyMediator;

 			if(!writeMediator) {
				writeMediator = new ReqMedicalMoneyMediator(view.medicalmoneyWriteView);
	 			facade.registerMediator(writeMediator);
			}
 			if(writeMediator) facade.sendNotification(MedicalMoneyFacade.LOAD_CONGMONEY_WRITE_INITCEHCK, oExport);
		}


		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
 		private function findCodeIndex(key:String, srcArr:ArrayCollection):int
		{
			for(var i:int=0; i<srcArr.length; i++) {
				if(srcArr[i].data == key) {
					return i;
				}
			}
			return -1;
		}

       private function get view():MedicalMoneyOverViewSac
        {
            return viewComponent as MedicalMoneyOverViewSac;
        }


	}
}